package com.time.company.app;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.StrictMode;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.sdk.QbSdk;
import com.time.company.R;
import com.time.company.db.DBUtil;
import com.time.company.db.ViewModelCreator;
import com.time.company.db.model.UserModel;
import com.time.company.servermodel.MyAddress;
import com.time.company.utils.SystemUtils;
import com.time.company.webserver.helper.glide.GlideAlbumLoader;
import com.yanzhenjie.album.Album;
import com.yanzhenjie.album.AlbumConfig;
import com.yanzhenjie.nohttp.InitializationConfig;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.OkHttpNetworkExecutor;
import com.youzan.androidsdk.YouzanSDK;
import com.youzan.androidsdk.basic.YouzanBasicSDKAdapter;

import org.litepal.LitePal;
import org.litepal.LitePalApplication;
import org.litepal.crud.DataSupport;

import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Bing on 2016/8/23.
 * E-mail is tx16bing@163.com
 */
public class MyApplication extends LitePalApplication {

    private final String TAG = getClass().getSimpleName();
    private static MyApplication instance;
    private AppConfig mConfig;
    private AddressManager am;
    private IWXAPI wxApi;

    private static final String USER_TYPE = "user_type";
    // 该字段用于每次更新后判断是否需要重新进入引导页
    private static final String IS_FIRST = "is_first";
    private static final String IS_LOGIN = "is_login";

    // login account
    private static final String USER_TELEPHONE = "telephone";
    // userId
    private static final String USER_ACCOUNT = "account";
    // token
    private static final String USER_TOKEN = "token";

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        am = AddressManager.getInstance();

        // Init LitePal 初始化数据库
        LitePal.initialize(instance);
        DBUtil.getInstance();
        mConfig = AppConfig.getInstance();

        //Init NoHttp 初始化网络引擎
        InitializationConfig config = InitializationConfig.newBuilder(this)
                // 全局连接服务器超时时间，单位毫秒，默认10s。
                .connectionTimeout(30 * 1000)
                // 全局等待服务器响应超时时间，单位毫秒，默认10s。
                .readTimeout(20 * 1000)
                // 配置网络层，默认URLConnectionNetworkExecutor，如果想用OkHttp：OkHttpNetworkExecutor。
                .networkExecutor(new OkHttpNetworkExecutor())
                .retry(2) // 全局重试次数，配置后每个请求失败都会重试n次。
                .build();
        NoHttp.initialize(config);
        Logger.setDebug(true);
        Logger.setTag(TAG);

        // Init jpush sdk
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        //设置标签
        Set<String> set = new HashSet<>();
        set.add("Time-company");
        JPushInterface.setTags(this, 0, set);

        // Init wx
        regToWx();
        regToSinaLogin();

        // VM会忽略文件URI曝光
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        // Album
        Album.initialize(AlbumConfig
                .newBuilder(instance)
                .setAlbumLoader(new GlideAlbumLoader())
                .setLocale(Locale.getDefault())
                .build());

        //WebView首次加载x5内核
        QbSdk.setDownloadWithoutWifi(true);
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onCoreInitFinished() {

            }

            @Override
            public void onViewInitFinished(boolean b) {

                //x5内核初始化完成的回调
                Logger.i("X5 init finished is " + b);
            }
        };
        QbSdk.initX5Environment(getApplicationContext(), cb);

        if (LeakCanary.isInAnalyzerProcess(this)) {
            return;
        }
        LeakCanary.install(this);

        // 初始化有赞
        YouzanSDK.init(this, getString(R.string.you_zan_client_id), new YouzanBasicSDKAdapter());
    }

    // 用于MultiDexEnable
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static MyApplication getInstance() {
        return instance;
    }


    public void setAppInfo(String userId, String telephone, boolean isLogin){
        setToken(userId);
        setAccount(userId);
        setTelephone(telephone);
        setLogin(isLogin);
    }

    public void initDir(){
        // 创建根目录
        mConfig.initDir();
    }

    // 注册到微信
    private void regToWx() {
        // 通过WXAPIFactory工厂，获取IWXAPI的实例微信
        wxApi = WXAPIFactory.createWXAPI(this, getString(R.string.wx_app_id), true);
        wxApi.registerApp(getString(R.string.wx_app_id));
        WXManager.instance().setApi(wxApi);
    }

    // 注册微博登录
    private void regToSinaLogin() {
        WbSdk.install(this,new AuthInfo(this,
                getString(R.string.sina_app_key),
                getString(R.string.sina_app_redirect_url),
                " "));
    }

    // 判断是否是主进程
    public boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = SystemUtils.getProcessName(this);
        return packageName.equals(processName);
    }

    public void exitApp() {
        DBUtil.getInstance().closeDB();
        MyManager.getInstance().clear();
        //销毁静态变量
        System.exit(0);
    }

    // 获取版本号
    public int getVersionCode() {
        try {
            PackageManager pm = getPackageManager();
            PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return -1;
        }
    }

    public String getTelephone() {
        String telephone = "";
        if (!TextUtils.isEmpty(ViewModelCreator.getInstance(this).getUserViewModel().getTelephone())) {
            telephone = ViewModelCreator.getInstance(this).getUserViewModel().getTelephone();
        }

        if (!TextUtils.isEmpty(mConfig.getString(USER_TELEPHONE, ""))) {
            telephone = mConfig.getString(USER_TELEPHONE, "");
        }

        return telephone;
    }

    public void setTelephone(String telephone) {
        mConfig.putString(USER_TELEPHONE, telephone);
    }

    public String getAccount() {
        return mConfig.getString(USER_ACCOUNT, "6");
    }

    public void setAccount(String account) {
        mConfig.putString(USER_ACCOUNT, account);
    }

    public String getToken() {
        return mConfig.getString(USER_TOKEN, "-1");
    }

    public void setToken(String token) {
        mConfig.putString(USER_TOKEN, token);
    }

    public String getUserType() {
        // 测试的时候用户类型用门店
        return mConfig.getString(USER_TYPE, "0");
    }

    public void setUserType(String type) {
        mConfig.putString(USER_TYPE, type);
    }

    public boolean isUser(){
        if (TextUtils.equals(getUserType(), getString(R.string.zero))) {
            return true;
        } else {
            return false;
        }
    }

    public boolean isFirst(){
        return mConfig.getBoolean(IS_FIRST, true);
    }

    public void setFirst(boolean first){
        mConfig.putBoolean(IS_FIRST, first);
    }

    public boolean isLogin() {
        return mConfig.getBoolean(IS_LOGIN, false);
    }

    public void setLogin(boolean login) {
        mConfig.putBoolean(IS_LOGIN, login);
    }

    public void initAddress(MyAddress address) {
        am.setAddress(address.getAddress());
        am.setLaunchPageAddress(address.getCompanyStartPage());
        am.setWebAddress(address.getCompanyAppFrontEndRootAddress());
        am.setUserRegisterProtocolAddress(address.getUserRegisterProtocolAddress());
        am.setCompanyRegisterProtocolAddress(address.getCompanyRegisterProtocolAddress());
        am.setCustomerServiceTelephoneNumbers(address.getCustomerServiceTelephoneNumbers());
    }

    public void destroyData() {
        // 停止推送服务
        JPushInterface.stopPush(this);
        setLogin(false);
        setToken("");
        setAccount("");
        // 清空当前账号的数据
//        clearSPData();

        // 清空数据库
        DataSupport.deleteAll(UserModel.class);
    }

    /**
     * 清空SharePreference数据
     */
    private void clearSPData() {
        SharedPreferences.Editor edit = mConfig.getPreferences().edit();
        edit.commit();
    }
}
